package com.example.lib_common.base

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.lib_net.model.api.BaseModel
import com.example.lib_net.model.api_mall.BaseMallModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch


/**
 * @author yaotianxue
 * @description ViewModel基类
 * @date 2025/1/14
 */
open class BaseViewModel: ViewModel() {
    /**
     * 第一套接口
     */
    fun <M:BaseModel<T>,T> execute(
        action: Flow<M>,
        onStart:(suspend ()->Unit)? = null,
        onError:(suspend (String)->Unit)? = null,
        onFinished:(suspend (M)->Unit)? = null,
    ) = viewModelScope.launch {
        action.onStart {
            onStart?.invoke()
        }.catch { err->
            onError?.invoke(err.message?:"")
        }.collectLatest {
            if(it.code === 0){
                onFinished?.invoke(it)
            }else{
                onError?.invoke(it.msg)
            }

        }
    }

    /**
     * 第二套接口
     */

    fun <M:BaseMallModel> executeMAllApi(
        action: Flow<M>,
        onStart:(suspend ()->Unit)? = null,
        onError:(suspend (String)->Unit)? = null,
        onFinished:(suspend (M)->Unit)? = null,
    ) = viewModelScope.launch {
        action.onStart {
            onStart?.invoke()
        }.catch { err->
            onError?.invoke(err.message?:"")
        }.collectLatest {
            if("SUCCESS" === it.code){
                onFinished?.invoke(it)
            }else{
               onError?.invoke(it.message.toString())
            }
        }
    }
}

